<script lang="ts" setup>
import { reactive, ref, watch } from "vue"
import {
  createOrderDataApi,
  updateOrderDataApi,
  getOrderDataApi,
  getOrderOneApi,
  downLoadOrderTable,
  getOrdeCode
} from "@/api/order"
import { type IGetOrderData } from "@/api/order/types/order"
import { type IGetComboData } from "@/api/combo/types/combo"
import { type FormInstance, type FormRules, ElMessage } from "element-plus"
import { Search, Refresh, CirclePlus, Download, RefreshRight, UploadFilled, Folder } from "@element-plus/icons-vue"
import { usePagination } from "@/hooks/usePagination"
import { useUserStore } from "@/store/modules/user"
// import { useCommonStore } from "@/store/modules/common"
import { useComboStore } from "@/store/modules/combo"
import { checkPhoneNumber, checkID, isAddressDetailed } from "@/utils/validate"
import { getToken } from "@/utils/cache/cookies"
import { IdCard } from "@/utils/getCardId"
import { uploadCidImageList } from "@/api/order"
import { getComboDataApi1 } from "@/api/combo"
import { formatDateTime } from "@/utils"

defineOptions({
  name: "OrderList"
})
const loading = ref<boolean>(false)
// const commonStore = useCommonStore()
const comboStore = useComboStore()
const comboList = ref<IGetComboData[]>([])
const comboList2 = ref<IGetComboData[]>([])
const payDate = ref("")
const seeState = ref("")
const comboStr = ref<string>("")
/**日期相关 */
const size = ref<"default" | "large" | "small">("default")
const shortcuts = [
  {
    text: "上周",
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: "上个月",
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  },
  {
    text: "三个月",
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    }
  }
]

/**END */
const uploadheaders = ref<any>({
  token: getToken()
})
const codeList = ref<any>([])
/**-------- */
const getCodeList = () => {
  getOrdeCode().then((res: any) => {
    // console.log(res)
    codeList.value = res.data
  })
}
getCodeList()
/**END */

const fileList0 = ref<any>([]) //身份证正面
const fileList1 = ref<any>([]) //身份证反面
const fileList2 = ref<any>([]) //人像
// ****************订单批量上传*******************************
import { genFileId } from "element-plus"
import type { UploadInstance, UploadProps, UploadRawFile } from "element-plus"

const upload = ref<UploadInstance>()

const handleExceed: UploadProps["onExceed"] = (files) => {
  upload.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  upload.value!.handleStart(file)
}
const handleSucc = () => {
  getTableData()
  // loading.value = false
  ElMessage.success("上传成功！")
}

const submitUpload = () => {
  // loading.value = true
  upload.value!.submit()
}
// *********************订单上传结束*************************

const formatterCombo = (row: any, column: any, celValue: any) => {
  comboList2.value.filter((item: any) => {
    if (item.id == row.sku) {
      celValue = item.name
    }
  })
  return celValue
}
const comboSkuToStr = (row: any) => {
  comboList.value.filter((item: any) => {
    if (item.id == row.sku) {
      comboStr.value = item.name
    }
  })
}

const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()

//#region 增
const dialogVisible = ref<boolean>(false)
const formRef = ref<FormInstance | null>(null)
const userStore = useUserStore()
// console.log(userStore.teamName)
const formData = reactive<any>({
  orderId: "",
  source: "",
  iccid: "",
  handleMobile: "",
  sku: "",
  heId: "",
  cardName: "",
  cardId: "",
  consignee: "",
  takeMobile: "",
  takeAddress: "",
  state: "",
  activate: "",
  kickback: "",
  superiorId: "",
  update: new Date(),
  superiorName: "",
  note: "",
  cardFront: "",
  cardBack: "",
  photo: "",
  chargingState: "",
  chargingDate: new Date(payDate.value),
  result: "",
  logisticsCompany: "",
  logisticsId: "",
  commissionState: "",
  recorder: "",
  salesman: "", //业务员
  remark: "", //备注
  //规则
  dataRole: "",
  //日期
  dayDate: "",
  //周
  startWeekDate: "",
  endWeekDate: "",
  //团队列表
  teamList: [],
  //订单状态
  orderState: ""
})
const formRules: FormRules = reactive({
  orderId: [{ required: true, trigger: "blur", message: "请输入订单名称" }],
  cardName: [{ required: true, trigger: "blur", message: "请填写姓名" }],
  consignee: [{ required: true, trigger: "blur", message: "请填写收货名" }],
  // sku: [{ required: true, trigger: "blur", message: "请选择套餐" }],
  // handleMobile: [{ required: true, validator: checkPhoneNumber, trigger: "blur" }],
  cardId: [{ required: true, validator: checkID, trigger: "blur" }],
  takeMobile: [{ required: true, validator: checkPhoneNumber, trigger: "blur" }],
  takeAddress: [{ required: true, validator: isAddressDetailed, trigger: "blur" }],

  team: [{ required: true, trigger: "blur", message: "请选择团队" }],
  dataRule: [{ required: true, trigger: "blur", message: "请选择规则" }],
  dataState: [{ required: false, trigger: "blur", message: "请选择状态" }]
})
const handleAdd = () => {
  seeState.value = "add"
  dialogVisible.value = true
}

const handleCreate = () => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      formData.chargingDate = payDate.value ? new Date(payDate.value) : null
      uploadFuc()
    } else {
      return false
    }
  })
}
const resetForm = () => {
  currentUpdateId.value = undefined
  clearValidate()
  formData.orderId = ""
  formData.handleMobile = ""
  formData.sku = ""
  formData.heId = ""
  formData.cardName = ""
  formData.cardId = ""
  formData.consignee = ""
  formData.takeMobile = ""
  formData.takeAddress = ""
  formData.cardFront = ""
  formData.cardBack = ""
  formData.photo = ""
  formData.chargingState = ""
  formData.chargingDate = new Date(payDate.value)
  formData.result = ""
  formData.logisticsCompany = ""
  formData.logisticsId = ""
  formData.commissionState = ""
  formData.teamList = []
  formData.dataRole = ""
  formData.dayDate = ""
  formData.startWeekDate = ""
  formData.endWeekDate = ""
  formData.orderState = ""
  formData.salesman = ""
  formData.remark = ""
  formData.active = ""
  fileList0.value = []
  fileList1.value = []
  fileList2.value = []
  isCard.value = false
  maxAge.value = 0
  minAge.value = 0
  isNoArea.value = ""
  comboStr.value = ""
  // selectedOptions.value = []
}
//#endregion

//#endregion

// row数据公用
const rowData = (row: any) => {
  currentUpdateId.value = row.id
  formData.orderId = row.orderId
  formData.source = row.source
  formData.iccid = row.iccid
  formData.handleMobile = row.handleMobile
  formData.sku = row.sku
  formData.heId = row.heId
  comboSkuToStr(row)
  formData.cardName = row.cardName
  formData.cardId = row.cardId
  formData.consignee = row.consignee
  formData.takeMobile = row.takeMobile
  formData.takeAddress = row.takeAddress
  formData.note = row.note
  formData.chargingState = row.chargingState
  payDate.value = !row.chargingDate ? row.chargingDate : null
  formData.result = row.result
  formData.recorder = row?.recorder
  formData.salesman = row?.salesman
  formData.remark = row?.remark
  formData.state = row?.state.code
  formData.active = row?.active
  formData.logisticsCompany = row.logisticsCompany
  formData.logisticsId = row.logisticsId
  formData.commissionState = row.commissionState
  if (row.cardFront) {
    fileList0.value = row.cardFront?.split(",").map((item: any) => {
      return {
        url: item
      }
    })
  } else {
    fileList0.value = []
  }

  // console.log(fileList0.value, 999)

  if (row.cardBack) {
    fileList1.value = row.cardBack?.split(",").map((item: any) => {
      return {
        url: item
      }
    })
  } else {
    fileList1.value = []
  }
  if (row.photo) {
    fileList2.value = row.photo?.split(",").map((item: any) => {
      return {
        url: item
      }
    })
  } else {
    fileList2.value = []
  }

  formData.cardBack = row.cardBack?.split("/image/")[1]
  formData.cardFront = row.cardFront?.split("/image/")[1]
  formData.photo = row.photo?.split("/image/")[1]
  dialogVisible.value = true
}

//#region 改
const updateType = ref<boolean>(false)
const currentUpdateId = ref<undefined | string>(undefined)
const handleUpdate = (row: IGetOrderData, type: any) => {
  seeState.value = "update"
  loading.value = true
  updateType.value = type
  getOrderOneApi({
    id: row.id
  }).then((res: any) => {
    rowData(res.data)
    loading.value = false
  })
}
//#endregion

//#region 查
const tableData = ref<IGetOrderData[]>([])
const searchFormRef = ref<FormInstance | null>(null)
const searchData = reactive({
  source: "",
  sku: "",
  cardName: "",
  orderOutId: "",
  handleMobile: "",
  cardId: "",
  takeMobile: "",
  searchDate: "",
  state: "",
  id: "",
  superName: ""
})
const getTableData = () => {
  getTableInfo(false)
}
/**方便下载订单功能将请求单拎出来 */
const getTableInfo = async (isDown: boolean) => {
  loading.value = true
  const page = ref<number>(paginationData.currentPage)
  const size = ref<number>(paginationData.pageSize)
  if (isDown) {
    page.value = 1
    size.value = 10000000
  } else {
    page.value = paginationData.currentPage
    size.value = paginationData.pageSize
  }
  await getOrderDataApi({
    page: page.value,
    size: size.value,
    source: searchData.source,
    cardName: searchData.cardName,
    orderOutId: searchData.orderOutId,
    handleMobile: searchData.handleMobile,
    cardId: searchData.cardId,
    takeMobile: searchData.takeMobile,
    sku: searchData.sku,
    start: new Date(searchData.searchDate[0]).getTime() || "",
    end: new Date(searchData.searchDate[1]).getTime() + 86400000 || "", //后端需要+一天时间戳
    state: searchData.state || 0,
    id: searchData.id,
    superName: searchData.superName,
    order_re_id: userStore.userInfo.user_id
  })
    .then((res) => {
      if (isDown) {
        // downInfo.value = res.data.list
      } else {
        paginationData.total = res.data.total
        tableData.value = res.data.list
      }
    })
    .catch(() => {
      tableData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}
const handleSearch = () => {
  if (paginationData.currentPage === 1) {
    getTableData()
  }
  paginationData.currentPage = 1
}
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  if (paginationData.currentPage === 1) {
    getTableData()
  }
  paginationData.currentPage = 1
}
const handleRefresh = () => {
  getTableData()
}

/**查看 详情 */

const handleSeeMore = (row: any) => {
  loading.value = true
  seeState.value = "see"
  getOrderOneApi({
    id: row.id
  }).then((res: any) => {
    rowData(res.data)
    loading.value = false
  })
}
//#endregion

/**  套餐切换 */
const isCard = ref<boolean>(false)
const maxAge = ref<number>(0)
const minAge = ref<number>(0)
const isNoArea = ref<any>("")
const noAreaFinallyArry = ref<any>([]) //不发货 省市区
const noAreaP = ref<any>([]) //不发货省
const noAreaPandC = ref<any>([]) //不发货省市
const noField = ref<any>([]) //敏感词
const comboChange = (val: any) => {
  // console.log(val)
  if (val) {
    const filterCombo = ref<any>(comboList.value.filter((item: any) => item.id + "" === val))
    isCard.value = filterCombo.value[0]?.card
    maxAge.value = filterCombo.value[0]?.maxAge
    minAge.value = filterCombo.value[0]?.minAge
    isNoArea.value = filterCombo.value[0]?.area
    noField.value = filterCombo.value[0]?.guide
    if (isNoArea.value) {
      const arr = JSON.parse(isNoArea.value.replace(/'/g, '"'))
      noAreaP.value = arr.filter((item: any) => item.length == 1).flat()
      noAreaPandC.value = arr.filter((item: any) => item.length == 2).map((item: any) => item.join(""))
      noAreaFinallyArry.value = arr.filter((item: any) => item.length == 3).map((item: any) => item.join(""))
    }
  } else {
    isCard.value = false
    maxAge.value = 60
    minAge.value = 16
    isNoArea.value = ""
  }
}

/** 图片改变 */
const handleChageImg = (file: any, resfileList: any) => {
  const size = ref(2)
  const fileSizeFlag = file.size / 1024 / 1024 < size.value
  if (!fileSizeFlag) {
    ElMessage.error(`请上传不大于${size.value}M的图片!`)
    fileList0.value = []
  } else {
    fileList0.value = resfileList
  }
}
const handleChageImg1 = (file: any, resfileList: any) => {
  const size = ref(2)
  const fileSizeFlag = file.size / 1024 / 1024 < size.value
  if (!fileSizeFlag) {
    ElMessage.error(`请上传不大于${size.value}M的图片!`)
    fileList1.value = []
  } else {
    fileList1.value = resfileList
  }
}
const handleChageImg2 = (file: any, resfileList: any) => {
  const size = ref(2)
  const fileSizeFlag = file.size / 1024 / 1024 < size.value
  if (!fileSizeFlag) {
    ElMessage.error(`请上传不大于${size.value}M的图片!`)
    fileList2.value = []
  } else {
    fileList2.value = resfileList
  }
}
// 移除图片
const handleRemove = (file: any) => {
  const list = fileList0.value
  for (const i in list) {
    if (list[i].uid === file.uid) {
      list.splice(i, 1)
    }
  }
  fileList0.value = list
}
// 移除图片
const handleRemove1 = (file: any) => {
  const list = fileList1.value
  for (const i in list) {
    if (list[i].uid === file.uid) {
      list.splice(i, 1)
    }
  }
  fileList1.value = list
}
// 移除图片
const handleRemove2 = (file: any) => {
  const list = fileList2.value
  for (const i in list) {
    if (list[i].uid === file.uid) {
      list.splice(i, 1)
    }
  }
  fileList2.value = list
}
//  确定上传
const uploadFuc = async () => {
  // console.log(fileList0.value)
  loading.value = true
  if ((fileList0.value.length === 0 || fileList1.value.length === 0 || fileList2.value.length === 0) && isCard.value) {
    ElMessage.error("请上传相关照片")
    loading.value = false
    return
  }
  const fileData = new FormData()
  const fileData1 = new FormData()
  const fileData2 = new FormData()
  fileList0.value.forEach((file: any) => {
    fileData.append("file", file.raw)
    fileData.append("name", formData.cardName)
  })
  fileList1.value.forEach((file: any) => {
    fileData1.append("file", file.raw)
    fileData1.append("name", formData.cardName)
  })
  fileList2.value.forEach((file: any) => {
    fileData2.append("file", file.raw)
    fileData2.append("name", formData.cardName)
  })
  if (!formData.sku && !formData.heId) {
    ElMessage.warning("请选择套餐或者合集套餐")
    loading.value = false
    return
  }
  const currentAge = Number(IdCard(formData.cardId, 3))
  if (!switchValue.value) {
    if (currentAge >= minAge.value && currentAge <= maxAge.value) {
      console.log("年龄核检通过")
    } else {
      ElMessage.error(`年龄限制为${minAge.value}-${maxAge.value}周岁，请核对身份证信息是否正确！`)
      loading.value = false
      return
    }
  }
  if (isCard.value) {
    if (fileList0.value[0].status === "ready") {
      await uploadCidImageList(fileData).then((res: any) => {
        if (res.code == 200) {
          formData.cardFront = res.data.split("/image/")[1]
          fileList0.value = []
        }
      })
    }
    if (fileList1.value[0].status === "ready") {
      await uploadCidImageList(fileData1).then((res: any) => {
        if (res.code == 200) {
          formData.cardBack = res.data.split("/image/")[1]
          fileList1.value = []
        }
      })
    }
    if (fileList2.value[0].status === "ready") {
      await uploadCidImageList(fileData2).then((res: any) => {
        if (res.code == 200) {
          formData.photo = res.data.split("/image/")[1]
          fileList2.value = []
        }
      })
    }
  }
  const inputArea = formData.takeAddress.trim().split(" ")
  /**不发货省 */
  if (noAreaP.value.length && !switchValue.value) {
    if (noAreaP.value.includes(inputArea[0])) {
      ElMessage.warning("填写的地址有误或在不发货地区喔！^-^")
      loading.value = false
      return
    }
  }
  /**不发货省市 */
  // console.log(noAreaPandC.value)
  if (noAreaPandC.value.length && !switchValue.value) {
    if (noAreaPandC.value.includes(`${inputArea[0]}${inputArea[1]}`)) {
      ElMessage.warning("填写的地址有误或在不发货地区喔！^-^")
      loading.value = false
      return
    }
  }
  /**不发货省市区 */
  // console.log(noAreaFinallyArry.value)

  if (noAreaFinallyArry.value.length && !switchValue.value) {
    if (noAreaFinallyArry.value.includes(`${inputArea[0]}${inputArea[1]}${inputArea[2]}`)) {
      ElMessage.warning("填写的地址有误或在不发货地区喔！^-^")
      loading.value = false
      return
    }
  }
  // if (noField.value && !switchValue.value) {
  //   const regex = new RegExp(noField.value.split(",").join("|"))
  //   if (regex.test(formData.takeAddress)) {
  //     ElMessage.warning("填写的地址含有敏感词！^-^")
  //     loading.value = false
  //     return
  //   }
  // }

  if (currentUpdateId.value === undefined) {
    await createOrderDataApi(
      {
        orderId: formData.orderId,
        source: formData.source,
        handleMobile: formData.handleMobile,
        sku: formData.sku,
        heId: formData.heId,
        cardName: formData.cardName,
        cardId: formData.cardId,
        consignee: formData.consignee,
        takeMobile: formData.takeMobile,
        takeAddress: formData.takeAddress,
        cardFront: formData.cardFront,
        cardBack: formData.cardBack,
        photo: formData.photo,
        recorder: formData.recorder,
        salesman: formData.salesman,
        remark: formData.remark,
        chargingState: formData.chargingState,
        chargingDate: formData.chargingDate,
        result: formData.result,
        logisticsCompany: formData.logisticsCompany,
        logisticsId: formData.logisticsId,
        commissionState: formData.commissionState,
        sync: true
      },
      userStore.userInfo.user_id,
      switchValue.value
    )
      .then(() => {
        ElMessage.success("新增成功")
        dialogVisible.value = false
        getTableData()
      })
      .finally(() => {
        loading.value = false
      })
  } else {
    await updateOrderDataApi(
      {
        id: currentUpdateId.value,
        orderId: formData.orderId,
        source: formData.source,
        iccid: formData.iccid,
        handleMobile: formData.handleMobile,
        sku: formData.sku,
        heId: formData.heId,
        cardName: formData.cardName,
        cardId: formData.cardId,
        consignee: formData.consignee,
        takeMobile: formData.takeMobile,
        takeAddress: formData.takeAddress,
        note: formData.note,
        cardFront: formData.cardFront,
        cardBack: formData.cardBack,
        photo: formData.photo,
        salesman: formData.salesman,
        remark: formData.remark,
        chargingState: formData.chargingState,
        recorder: formData.recorder,
        // chargingDate: formData.chargingDate,
        result: formData.result,
        logisticsCompany: formData.logisticsCompany,
        logisticsId: formData.logisticsId,
        commissionState: formData.commissionState
        // update: formData.update
      },
      updateType.value
    )
      .then(() => {
        ElMessage.success("修改成功")
        dialogVisible.value = false
        getTableData()
      })
      .finally(() => {
        loading.value = false
      })
  }
}
/** 订单下载 默认下载所有数据，查询后下载所有符合查询条件的数据*/
// const dialogVisible3 = ref<boolean>(false)

const downLoad = async () => {
  // console.log(formData1.downArr, "传送订单")
  downLoadOrderTable({
    // source: searchData.source,
    order_card_name: searchData.cardName,
    orderOutId: searchData.orderOutId,
    handleMobile: searchData.handleMobile,
    cardId: searchData.cardId,
    takeMobile: searchData.takeMobile,
    order_sku: searchData.sku,
    start: new Date(searchData.searchDate[0]).getTime() || "",
    end: new Date(searchData.searchDate[1]).getTime() + 86400000 || "", //后端需要+一天时间戳
    order_state: searchData.state || 0,
    id: searchData.id,
    // superName: searchData.superName,
    order_re_id: userStore.userInfo.user_id
  })
    .then((res: any) => {
      const blob = new Blob([res.data], {
        type: "application/xlsx;charset=utf-8"
      })
      // console.log(res)
      const downloadElement = document.createElement("a")
      const href = window.URL.createObjectURL(blob)
      downloadElement.href = href
      downloadElement.download = "订单.xlsx"
      document.body.appendChild(downloadElement)
      downloadElement.click()
      window.URL.revokeObjectURL(href)
      // formData1.download = ""
    })
    .finally(() => {
      loading.value = false
    })
}
//合集套餐
import { getCompailationDataApi } from "@/api/combo"
const switchValue = ref<any>(false)
const comboHJList = ref<any>([])
const getComboHjList = () => {
  getCompailationDataApi({
    page: 1,
    size: 1000,
    name: ""
  })
    .then((res: any) => {
      comboHJList.value = res.data.data.list
    })
    .catch(() => {
      comboHJList.value = []
    })
}
getComboHjList()
const changeComboType = () => {
  formData.sku = ""
  formData.heId = ""
}
// const handleDownLoad = () => {
//   const basePW = atob(commonStore.DOWNLOADWORD)
//   if (formData1.download !== basePW) {
//     ElMessage.error("密码错误，请重新输入！")
//     formData1.download = ""
//   } else {
//     loading.value = true
//     downLoadOrderTable({
//       ids: formData1.downArr
//     })
//       .then((res: any) => {
//         const blob = new Blob([res.data], {
//           type: "application/xlsx;charset=utf-8"
//         })
//         // console.log(res)
//         const downloadElement = document.createElement("a")
//         const href = window.URL.createObjectURL(blob)
//         downloadElement.href = href
//         downloadElement.download = "订单.xlsx"
//         document.body.appendChild(downloadElement)
//         downloadElement.click()
//         window.URL.revokeObjectURL(href)
//         // dialogVisible3.value = false
//         formData1.download = ""
//       })
//       .finally(() => {
//         loading.value = false
//       })
//   }
// }
/** 订单下载 END*/

/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })
/** 监听套餐数据是否变化 */
watch([() => formData.sku], (newValue) => comboChange(newValue.join()))
/**监听套餐缓存(pinia) */
const comboList1 = ref<any>([])
comboStore.getComoboFn()
watch(
  [() => comboStore.comboListStore],
  (newValue) => {
    comboList.value = newValue.flat()
    comboList1.value = newValue.flat().filter((item) => item.state === "true")
  },
  {
    immediate: true
  }
)

const getComoboFn = async () => {
  await getComboDataApi1({}).then((res: any) => {
    comboList2.value = res.data
  })
}
getComoboFn()

/**E N D */
// ** 清除规则报错信息
const clearValidate = () => {
  formRef.value?.clearValidate()
}
</script>

<template>
  <div class="app-container">
    <el-card v-loading="loading" shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="id" label="订单ID">
          <el-input v-model="searchData.id" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="orderOutId" label="订单外部ID">
          <el-input v-model="searchData.orderOutId" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="cardName" label="身份证名字">
          <el-input v-model="searchData.cardName" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="cardId" label="身份证号">
          <el-input v-model="searchData.cardId" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="handleMobile" label="办理手机号">
          <el-input v-model="searchData.handleMobile" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="takeMobile" label="收件电话">
          <el-input v-model="searchData.takeMobile" placeholder="请输入" />
        </el-form-item>
        <!-- <el-form-item prop="source" label="订单来源">
          <el-input v-model="searchData.source" placeholder="请输入" />
        </el-form-item> -->
        <el-form-item prop="superName" label="上级名">
          <el-input v-model="searchData.superName" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="sku" label="套餐">
          <!-- <el-input v-model="searchData.sku" placeholder="请输入" /> -->
          <el-select v-model="searchData.sku" clearable placeholder="请选套餐" style="width: 240px">
            <el-option v-for="item in comboList2" :key="item.id" :label="item.name" :value="item.id + ''" />
          </el-select>
        </el-form-item>
        <el-form-item prop="state" label="状态">
          <!-- <el-input v-model="searchData.sku" placeholder="请输入" /> -->
          <el-select v-model="searchData.state" clearable placeholder="请选择" style="width: 240px">
            <el-option v-for="item in codeList" :key="item.code" :label="item.state" :value="item.code" />
          </el-select>
        </el-form-item>
        <el-form-item prop="searchDate" label="订单日期">
          <el-date-picker v-model="searchData.searchDate" type="daterange" unlink-panels range-separator="至"
            start-placeholder="开始时间" end-placeholder="结束时间" :shortcuts="shortcuts" :size="size" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card v-loading="loading" shadow="never">
      <div class="toolbar-wrapper">
        <el-button type="primary" :icon="CirclePlus" @click="handleAdd">添加订单</el-button>
        <div style="display: none">
          <!-- <el-button type="danger" :icon="UploadFilled">批量上传</el-button> -->
          <el-upload ref="upload" class="upload-demo" action="api/order/upload" :limit="1" :headers="uploadheaders"
            :on-exceed="handleExceed" :on-success="handleSucc" :auto-upload="false"
            style="display: inline-block; vertical-align: top; margin-left: 10px">
            <template #trigger>
              <el-button type="danger" :icon="Folder">选择文件</el-button>
            </template>
            <el-button style="vertical-align: top" class="ml-3" type="success" :icon="UploadFilled"
              @click="submitUpload">
              批量上传
            </el-button>
          </el-upload>
          <el-link type="primary" :icon="Download" style="margin-left: 50px" href="api/order/down/downTemplate"
            Download>下载模版</el-link>
        </div>
        <div>
          <el-tooltip content="下载">
            <el-button type="primary" :icon="Download" circle @click="downLoad" />
          </el-tooltip>
          <el-tooltip content="刷新表格">
            <el-button type="primary" :icon="RefreshRight" circle @click="handleRefresh" />
          </el-tooltip>
        </div>
      </div>
      <div class="table-wrapper">
        <el-table :data="tableData" v-horizontal-scroll="'always'">
          <!-- <el-table-column type="selection" width="50" align="center" /> -->
          <el-table-column prop="id" label="ID" align="center" />
          <el-table-column prop="orderId" label="外部ID" align="center" />
          <el-table-column prop="create" label="创建时间" align="center">
            <template #default="scope">
              {{ formatDateTime(scope.row.create) }}
            </template>
          </el-table-column>
          <el-table-column prop="update" label="反馈时间" align="center">
            <template #default="scope">
              {{ formatDateTime(scope.row.update) }}
            </template>
          </el-table-column>
          <el-table-column prop="source" label="订单来源" align="center" />
          <el-table-column prop="sku" label="套餐" align="center" :formatter="formatterCombo" width="200" />
          <el-table-column prop="handleMobile" label="入网号" align="center" />
          <!-- <el-table-column prop="iccid" label="ICCID" align="center" /> -->
          <el-table-column prop="cardName" label="姓名" align="center" />
          <el-table-column prop="cardId" label="身份证号" align="center" />
          <el-table-column prop="consignee" label="收货人" align="center" />
          <el-table-column prop="takeMobile" label="收货电话" align="center" />
          <el-table-column prop="money" label="预结算金额" align="center" width="130" />
          <el-table-column prop="takeAddress" label="收货地址" align="center" show-overflow-tooltip />
          <el-table-column label="订单状态" align="center">
            <template #default="scope">
              <div :class="{
                doing: scope.row.state.code <= 200 && scope.row.state.code > 199,
                success: scope.row.state.code >= 100 && scope.row.state.code < 200,
                error: scope.row.state.code >= 400,
                again: scope.row.state.code < 0
              }">
                {{ scope.row.state.state }}
                <div class="text-ellipsis" v-if="scope.row.result" style="font-size: 12px">
                  <el-tooltip placement="top">
                    <template #content> {{ scope.row.result }} </template>
                    <span style="cursor: pointer">({{ scope.row.result }})</span>
                  </el-tooltip>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="active" label="激活时间" align="center">
            <template #default="scope">
              {{ formatDateTime(scope.row.active) }}
            </template>
          </el-table-column>
          <el-table-column label="物流状态" align="center" show-overflow-tooltip>
            <template #default="scope">
              {{ scope.row.logisticsState.str }}
            </template>
          </el-table-column>
          <el-table-column prop="chargingState" label="充值情况" align="center" show-overflow-tooltip />
          <!-- <el-table-column prop="superiorName" label="上级名" align="center" /> -->
          <el-table-column fixed="right" label="操作" width="100" align="center">
            <template #default="scope">
              <el-button type="primary" text bg size="small" @click="handleUpdate(scope.row, true)"
                :disabled="scope.row.state.code < 400">重新提交</el-button><br />
              <el-button v-if="scope.row.state?.code == 402 || scope.row.state?.code == 401" type="primary" text bg
                size="small" @click="handleUpdate(scope.row, false)">再次提交</el-button>
              <br />
              <el-button type="primary" text bg size="small" @click="handleSeeMore(scope.row)"> 查看详情</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination background :layout="paginationData.layout" :page-sizes="paginationData.pageSizes"
          :total="paginationData.total" :page-size="paginationData.pageSize" :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>
    <!-- 新增/修改 -->
    <el-dialog v-model="dialogVisible"
      :title="seeState === 'see' ? '查看详情' : currentUpdateId === undefined ? '新增订单' : '修改订单'" @close="resetForm"
      width="80%" v-if="seeState !== 'data' && seeState !== 'dataShow'">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" label-position="left">
        <el-form-item prop="orderId" label="订单外部ID">
          <el-input v-model="formData.orderId" placeholder="请输入" :disabled="seeState === 'see'" />
        </el-form-item>
        <!--        <el-form-item prop="source" label="订单来源">-->
        <!--          <el-input v-model="formData.source" placeholder="请输入" disabled />-->
        <!--        </el-form-item>-->
        <el-form-item prop="recorder" label="录单员" v-if="seeState === 'see'">
          <el-input v-model="formData.recorder" placeholder="请输入" disabled />
        </el-form-item>
        <el-form-item prop="recorder" label="发展业务员">
          <el-input v-model="formData.salesman" placeholder="请输入" :disabled="seeState === 'see'" />
        </el-form-item>
        <el-form-item prop="recorder" label="备注">
          <el-input v-model="formData.remark" placeholder="请输入" :disabled="seeState === 'see'" />
        </el-form-item>
        <el-form-item prop="state" label="状态" v-if="seeState === 'see'">
          <!-- <el-input v-model="searchData.sku" placeholder="请输入" /> -->
          <el-select v-model="formData.state" clearable placeholder="请选择" style="width: 240px"
            :disabled="seeState === 'see'">
            <el-option v-for="item in codeList" :key="item.code" :label="item.state" :value="item.code" />
          </el-select>
        </el-form-item>
        <el-form-item prop="active" label="激活时间">
         <span>{{ formatDateTime(formData.active) }}</span>
        </el-form-item>
        <el-form-item prop="sku" label="订购的套餐">
          <el-input type="textarea" disabled v-if="seeState === 'see'" v-model="comboStr" />
          <el-select v-if="!switchValue && seeState !== 'see'" v-model="formData.sku" clearable filterable
            placeholder="请选套餐,可输入快速查询" style="width: 80%">
            <el-option v-for="item in comboList1" :key="item.id" :label="item.name" :value="item.id + ''" />
          </el-select>
          <el-select v-if="switchValue && seeState !== 'see'" v-model="formData.heId" clearable filterable
            placeholder="请选合集套餐,可输入快速查询" style="width: 80%">
            <!-- :value="item.id + ''" -->
            <el-option v-for="item in comboHJList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
          <span v-if="seeState !== 'see'" style="margin-left: 10px">切换为合集套餐 <el-switch v-model="switchValue"
              @change="changeComboType" /></span>
        </el-form-item>
        <el-form-item prop="handleMobile" label="办理手机号" v-if="seeState === 'see'">
          <el-input v-model="formData.handleMobile" :disabled="seeState === 'see'" placeholder="请输入" maxlength="11"
            show-word-limit />
        </el-form-item>
        <el-form-item prop="iccid" label="ICCID" v-if="seeState === 'see'">
          <el-input v-model="formData.iccid" :disabled="seeState === 'see'" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="cardName" label="身份证姓名">
          <el-input v-model="formData.cardName" :disabled="seeState === 'see'" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="cardId" label="身份证号">
          <el-input v-model="formData.cardId" :disabled="seeState === 'see'" placeholder="请输入" maxlength="18"
            show-word-limit />
        </el-form-item>
        <el-form-item prop="chargingState" label="充值情况" v-if="seeState === 'see'">
          <el-input autosize type="textarea" :disabled="seeState === 'see'" v-model="formData.chargingState"
            placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="chargingDate" label="充值时间" v-if="seeState === 'see'">
          <el-date-picker v-model="payDate" :disabled="seeState === 'see'" type="datetime" placeholder="请选择时间" />
        </el-form-item>
        <el-form-item prop="result" label="结果描述" v-if="seeState === 'see'">
          <el-input v-model="formData.result" :disabled="seeState === 'see'" autosize type="textarea"
            placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="logisticsCompany" label="物流公司" v-if="seeState !== 'add'">
          <el-input v-model="formData.logisticsCompany" :disabled="seeState === 'see'" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="logisticsId" label="物流单号" v-if="seeState !== 'add'">
          <el-input v-model="formData.logisticsId" :disabled="seeState === 'see'" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="activate" label="激活数据" v-if="seeState === 'see'">
          <el-input v-model="formData.activate" type="textarea" placeholder="请输入" :disabled="seeState === 'see'" />
        </el-form-item>
        <el-form-item prop="kickback" label="结佣数据" v-if="seeState === 'see'">
          <el-input v-model="formData.kickback" type="textarea" placeholder="请输入" :disabled="seeState === 'see'" />
        </el-form-item>
        <el-form-item prop="commissionState" label="佣金状态" v-if="seeState === 'see'">
          <el-input v-model="formData.commissionState" :disabled="seeState === 'see'" type="textarea" autosize
            placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="consignee" label="收货人">
          <el-input v-model="formData.consignee" :disabled="seeState === 'see'" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="takeMobile" label="收货电话">
          <el-input v-model="formData.takeMobile" :disabled="seeState === 'see'" placeholder="请输入" maxlength="11"
            show-word-limit />
        </el-form-item>
        <el-form-item prop="takeAddress">
          <template #label>
            <span>收货地址</span>
            <el-tooltip class="box-item" effect="customized" placement="bottom">
              <template #content>
                地址格式：某某省 某某市 某某区 详细地址<br />
                例如 河南省 焦作市 山阳区 新新家园某某楼503<br />
                格式不正确不予通过
              </template>
              <el-icon style="cursor: pointer">
                <InfoFilled />
              </el-icon>
            </el-tooltip>
          </template>
          <el-input v-model="formData.takeAddress" :disabled="seeState === 'see'" placeholder="请按照提示格式填写" />
        </el-form-item>
        <el-form-item v-if="isCard" prop="cardFront" label="身份证正面照">
          <el-upload :auto-upload="false" :file-list="fileList0" :show-file-list="true" list-type="picture-card"
            :limit="1" accept="image/*" :on-change="handleChageImg" :disabled="fileList0.length !== 0">
            <el-icon>
              <Plus />
            </el-icon>
            <template #file="{ file }">
              <div>
                <img class="el-upload-list__item-thumbnail" :src="file.url" />
                <span class="el-upload-list__item-actions">
                  <span class="el-upload-list__item-delete" @click="handleRemove(file)" v-if="seeState !== 'see'">
                    <el-icon>
                      <Delete />
                    </el-icon>
                  </span>
                </span>
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item v-if="isCard" prop="cardBack" label="身份证反面照">
          <el-upload :auto-upload="false" :file-list="fileList1" :show-file-list="true" list-type="picture-card"
            :limit="1" accept="image/*" :on-change="handleChageImg1" :disabled="fileList1.length !== 0">
            <el-icon>
              <Plus />
            </el-icon>
            <template #file="{ file }">
              <div>
                <img class="el-upload-list__item-thumbnail" :src="file.url" />
                <span class="el-upload-list__item-actions">
                  <span class="el-upload-list__item-delete" @click="handleRemove1(file)" v-if="seeState !== 'see'">
                    <el-icon>
                      <Delete />
                    </el-icon>
                  </span>
                </span>
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item v-if="isCard" prop="photo" label="人像照片">
          <el-upload :auto-upload="false" :file-list="fileList2" :show-file-list="true" list-type="picture-card"
            :limit="1" accept="image/*" :on-change="handleChageImg2" :disabled="fileList2.length !== 0">
            <el-icon>
              <Plus />
            </el-icon>
            <template #file="{ file }">
              <div>
                <img class="el-upload-list__item-thumbnail" :src="file.url" />
                <span class="el-upload-list__item-actions">
                  <span class="el-upload-list__item-delete" @click="handleRemove2(file)" v-if="seeState !== 'see'">
                    <el-icon>
                      <Delete />
                    </el-icon>
                  </span>
                </span>
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false" v-if="seeState !== 'see'">取消</el-button>
        <el-button type="primary" @click="handleCreate" v-if="seeState !== 'see'" :disabled="loading">确认</el-button>
      </template>
    </el-dialog>
    <!-- 批量下载 -->
    <!-- <el-dialog v-model="dialogVisible3" title="下载密码" @close="resetForm1" width="50%" v-loading="loading">
      <el-form
        ref="formRef"
        :model="formData1"
        :rules="formRules1"
        label-width="100px"
        label-position="left"
        @keyup.enter="handleDownLoad"
      >
        <el-form-item prop="download" label="下载密码">
          <el-input v-model="formData1.download" placeholder="请输入下载密码" type="password" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible3 = false">取消</el-button>
        <el-button type="primary" @click="handleDownLoad">确认</el-button>
      </template>
    </el-dialog> -->
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;

  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}

:deep(.el-upload-list__item .el-icon--close-tip) {
  top: 20px;
  left: 10px;
  right: 0;
}

.doing {
  color: #b88230;
}

.error {
  color: red;
}

.success {
  color: #67c23a;
}

.again {
  color: #c45656;
}

:deep(.el-popper) {
  max-width: 50% !important;
}

.date-box {
  width: 340px !important;
}

.text-ellipsis {
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  -webkit-line-clamp: 3;
  display: -webkit-box;
  -webkit-box-orient: vertical;
}

:deep(.el-loading-parent--relative) {
  z-index: 199999 !important;
}
</style>
<style>
.el-popper.is-customized {
  /* Set padding to ensure the height is 32px */
  padding: 6px 12px;
  background: linear-gradient(90deg, rgb(159, 229, 151), rgb(204, 229, 129));
}

.el-popper.is-customized .el-popper__arrow::before {
  background: linear-gradient(45deg, #b2e68d, #bce689);
  right: 0;
}
</style>
